package org.gpf;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class DOM4J_Test {

	public static void main(String[] args) throws Exception {

		dom4jParser("res/books.xml");
		newXml("res/books_dom4j_out.xml");
	}

	private static void newXml(String url) throws IOException {
		
		Document document = DocumentHelper.createDocument();
		Element books = document.addElement("books");
		Element book = books.addElement("book");
		book.addAttribute("id", "001");
		book.addAttribute("isbn", "1");
		Element name = book.addElement("name");
		Element author = book.addElement("author");
		Element year = book.addElement("year");
		Element price = book.addElement("price");
		name.setText("面向对象程序设计");
		author.setText("同慕斯");
		year.setText("2014");
		price.setText("99.6");
		
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setIndent(true);
		format.setEncoding("utf-8");
		
		XMLWriter writer = new XMLWriter(new FileWriter(url), format);
		writer.write(document);
		writer.close();
	}

	private static void dom4jParser(String url) throws Exception {
		
		SAXReader reader = new SAXReader(); // 创建SAXReader
		Document document = reader.read(url);// 加载xml文档，获得document对象
		Element books = document.getRootElement();// 获取根节点
		Iterator<Element> iterator = books.elementIterator();// 获取迭代器
		while (iterator.hasNext()) {
			Element book = iterator.next();
			List<Attribute>bookAttrs = book.attributes(); // 得到属性集合
			for (Attribute attr : bookAttrs) {
				System.out.println("属性名：" + attr.getName() + "，属性值：" + attr.getValue());
			}
			// 获取book的子节点
			Iterator<Element> it = book.elementIterator();
			while (it.hasNext()) {
				Element element = it.next();
				System.out.println("节点名：" + element.getName() + ",节点值：" + element.getText());
			}
		}
	}

}
